package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.StudyEntity;
import com.hctforgreen.greenservice.ui.adapter.StudyListAdapter;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

import org.taptwo.android.widget.MyXListView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 新学员培训--学习资料
 */
public class NewStudentTrainActivity extends ParentActivity implements
        MyXListView.IXListViewListener {
    private int pageNum = 1;// 当前页 初始值为1
    private MyXListView listView;
    private StudyListAdapter mAdapter;
    private List<StudyEntity> data = new ArrayList<StudyEntity>();

    private String studyTypeId;
    private String childtypeId;
    private String searchKey;
    private String trainType;

    private long mLExitTime = 0;
    private final long mLDelayTime = 2000;

    private DownloadUpdateReceiver mUpdateReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study_list);

        initSkinLayout();
        initTitleButtonBar();
        initDownloadUpdateReceiver();
        initDataAndWindow();
    }

    protected void onDestroy() {
        if (mUpdateReceiver != null) {
            unregisterReceiver(mUpdateReceiver);
        }
        super.onDestroy();
    }

    private void initDataAndWindow() {

        studyTypeId = getIntent().getStringExtra("studyTypeId");
        childtypeId = getIntent().getStringExtra("childtypeId");
        searchKey = getIntent().getStringExtra("searchKey");
        trainType = getIntent().getStringExtra("trainType");

        final View convertView = findViewById(R.id.lyt_default_content);
        listView = (MyXListView) convertView.findViewById(R.id.lst_default_list);
        listView.setPullRefreshEnable(true);
        listView.setPullLoadEnable(true);
        listView.setXListViewListener(this);
        mAdapter = new StudyListAdapter(NewStudentTrainActivity.this, data, listView);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(NewStudentTrainActivity.this, NewStudentDetailActivity.class);
                intent.putExtra(HctConstants.ON_ACTIVITY_KEY_STUDY_ENTITY, data.get(position - 1));
                startActivity(intent);
            }
        });
        final View loadView = convertView.findViewById(R.id.lyt_default_list_load);
        // mAdapter = new VideoDetailAdapter(LearningListActivity.this, data,
        // gridView.getRefreshableView());
        // gridView.getRefreshableView().setAdapter(mAdapter);
        // gridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
        //
        // @Override
        // public void onPullDownToRefresh(
        // PullToRefreshBase<GridView> refreshView) {// 下拉刷新
        // pageNum = 1;
        // initData(gridView, loadView, typeId, null, false);
        // }
        //
        // @Override
        // public void onPullUpToRefresh(
        // PullToRefreshBase<GridView> refreshView) {// 上拉加载更多
        // pageNum++;
        // initData(gridView, loadView, typeId, null, false);
        // }
        //
        // });
        //
        initData(loadView, true);

    }

    private void initData(final View loadView, final boolean showLoadView) {
        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                switch (msg.what) {

                    case HctConstants.STATUS_FAILD:
                        if (pageNum == 1) {
                            data.clear();
                            mAdapter.notifyDataSetChanged();
                            listView.requestFailed();
                        }
                        break;
                    case HctConstants.STATUS_SUCCESS:
                        HctResult hctResult = (HctResult) msg.obj;
                        if (hctResult != null && hctResult.data != null) {
                            List<StudyEntity> netData = (List<StudyEntity>) hctResult.data;
                            if (netData != null && netData.size() > 0) {
                                if (pageNum > 1) {// 加载更多
                                    data.addAll(netData);
                                } else {// 首页数据
                                    data.clear();
                                    data.addAll(netData);
                                }
                                if (netData.size() < 20) {
                                    listView.setPullLoadEnable(false);
                                }
                            } else {
                                listView.setPullLoadEnable(false);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                        new Thread() {
                            public void run() {
                                HctController controller = new HctController(NewStudentTrainActivity.this);
                                try {
                                    controller.getNewStudyDataListByPersonId(studyTypeId, childtypeId, searchKey,
                                            "1", pageNum + "", LoginResultStoreUtil.get(NewStudentTrainActivity.this).personId);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        break;
                    default:
                        break;
                }
                loadView.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                if (pageNum == 1) {
                    listView.stopRefresh();
                } else {
                    listView.stopLoadMore();
                }
                super.dispatchMessage(msg);
            }
        };

        if (showLoadView) {
            loadView.setVisibility(View.VISIBLE);
        }
        new Thread() {
            public void run() {
                HctController controller = new HctController(
                        NewStudentTrainActivity.this);
                try {
                    HctResult hctResult = controller.getNewPersonStudyDataList(studyTypeId, childtypeId, searchKey,
                                    "1", pageNum + "", trainType);
                    handler.sendMessage(handler.obtainMessage(HctConstants.STATUS_SUCCESS, hctResult));
                } catch (Exception e) {
                    handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
                    e.printStackTrace();
                }
            }
        }.start();
//        new Thread() {
//            public void run() {
//                HctController controller = new HctController(
//                        NewStudentTrainActivity.this);
//                try {
//                    HctResult hctResult = controller
//                            .getNewStudyDataListByPersonId(studyTypeId, childtypeId, searchKey,
//                                    "1", pageNum + "", LoginResultStoreUtil.get(NewStudentTrainActivity.this).personId);
//                    handler.sendMessage(handler.obtainMessage(
//                            HctConstants.STATUS_SUCCESS, hctResult));
//
//
//                } catch (Exception e) {
//                    handler.sendEmptyMessage(HctConstants.STATUS_FAILD);
//                    e.printStackTrace();
//                }
//            }
//        }.start();


    }

    /**
     * 初始化标题栏
     */
    private void initTitleButtonBar() {
        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        titleTv.setText(getString(R.string.train_new_training));
        final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void onRefresh() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        listView.setRefreshTime(dateFormat.format(new Date()));
        pageNum = 1;
        initData(getLoadView(), false);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        initData(getLoadView(), false);
    }

    private View getLoadView() {
        View convertView = findViewById(R.id.lyt_default_content);
        return convertView.findViewById(R.id.lyt_default_list_load);
    }

    public class DownloadUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String downloadUrl = intent.getStringExtra(HctConstants.ON_DOWNLOAD_SERIVE_KEY_DOWNLOAD_URL);
            boolean bSwitchDownloadState = intent.getBooleanExtra(HctConstants.ON_DOWNLOAD_SERIVE_KEY_SWITCH_DOWNLOAD_STATE, false);
            if (bSwitchDownloadState) {
                mAdapter.updateView(downloadUrl);
                return;
            }
            if (!bSwitchDownloadState && ((System.currentTimeMillis() - mLExitTime) > mLDelayTime)) {
                mLExitTime = System.currentTimeMillis();
                mAdapter.updateView(downloadUrl);
            }
        }
    }

    private void initDownloadUpdateReceiver() {
        /**
         * 注册下载进度条的监听,在BookShelfAdapter中实现
         */
        mUpdateReceiver = new DownloadUpdateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(HctConstants.RECEIVER_BOOKSHELF_ACTIVITY_DOWNLOAD_UPDATE);
        registerReceiver(mUpdateReceiver, filter);
    }
}
